package com.wswy.wyjk.core.location;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;

public class LocationLoader implements AMapLocationListener {

  private static final String TAG = "LocationLoader";

  public static void load(Context context,OnLocationCallback callback){
    LocationLoader locationLoader = new LocationLoader(context.getApplicationContext());
    locationLoader.setCallback(callback);
    locationLoader.start();
  }



  private AMapLocationClient mLocationClient = null;

  private OnLocationCallback mCallback;

  public LocationLoader(Context context) {
    mLocationClient = new AMapLocationClient(context.getApplicationContext());
    AMapLocationClientOption option = new AMapLocationClientOption();

    option.setLocationMode(AMapLocationMode.Battery_Saving);
    option.setOnceLocation(true);
    option.setNeedAddress(true);

    mLocationClient.setLocationListener(this);


    mLocationClient.setLocationOption(option);

  }


  public void setCallback(OnLocationCallback callback) {
    this.mCallback = callback;
  }

  public void start(){

    mLocationClient.stopLocation();
    mLocationClient.startLocation();

  }




  @Override
  public void onLocationChanged(AMapLocation aMapLocation) {
    mLocationClient.stopLocation();

    if (aMapLocation != null){
      if (aMapLocation.getErrorCode()  == 0){

        LocationModel locationModel = new LocationModel();

        locationModel.latitude = aMapLocation.getLatitude();
        locationModel.longitude = aMapLocation.getLongitude();

        locationModel.country = aMapLocation.getCountry();

        locationModel.province = aMapLocation.getProvince();

        locationModel.city = removeSuffix(aMapLocation.getCity());
        locationModel.cityCode = aMapLocation.getCityCode();
        locationModel.adCode = aMapLocation.getAdCode();

        locationModel.district = aMapLocation.getDistrict();
        locationModel.street = aMapLocation.getStreet();

        locationModel.address = aMapLocation.getAddress();

        if(mCallback != null){
          mCallback.onLoaded(locationModel);
        }

      } else {
        Log.e(TAG,"location Error, ErrCode:"
            + aMapLocation.getErrorCode() + ", errInfo:"
            + aMapLocation.getErrorInfo());
      }
    }


  }

  private String removeSuffix(String city){
    if (TextUtils.isEmpty(city)){
      return city;
    }
    int len = city.length();
    if (city.endsWith("市") && len>=3){
      return city.substring(0,len-1);
    }
    return city;

  }

  public void find(){

  }

  public interface OnLocationCallback{
    void onLoaded(LocationModel locationModel);
  }

}
